<template>
<a-card>
  <template #title>
    <CommentOutlined />
    评论 ({{ commentCount }})
  </template>
  <PublishComment :blog-id="blogId" @push="confirmPush" />
  <Loading :loading="loading">
    <CommentItem :author="authorId"
                 v-for="comment in commentList"
                 @reload="getComments"
                 :comments="comment"/>
    <a-empty v-if="commentList.length === 0" description="暂无评论" />
  </Loading>
</a-card>
</template>

<script setup>
import {CommentOutlined} from "@ant-design/icons-vue";
import CommentItem from "./CommentItem.vue";
import PublishComment from "./PublishComment.vue";
import {apiGet, apiPost} from "../../../../fentch";
import {message} from "ant-design-vue";
import {onMounted, ref, watch} from "vue";
import Loading from "../../../commons/Loading.vue";

const props = defineProps({
  commentCount: {
    type: Number,
    default: 0
  },
  blogId: {
    type: Number,
    required: true,
    default: 0
  },
  authorId: {
    type: Number,
    required: true,
    default: 0
  }
})
// 获取当前账户
const userInfo = JSON.parse(window.localStorage.getItem('user'))

// 评论列表
const commentList = ref([])
// 响应式作者
const authorId = ref(0)
/**
 * Loading
 * @param form
 */
const loading = ref(false)

// 发布评论
const confirmPush = form => {
  apiPost(`/comments/${props.blogId}`, {
    anonymous: form.anonymous,
    content: form.comment,
    reply_id: null
  }).then(res => {
    if (res.data.code === 0) {
      message.success('发布成功')
      getComments()
      return
    }
    message.error(res.data.message)
  })
}

/**
 * 获取评论数据
 */
const getComments = () => {
  loading.value = true
  apiGet(`/comments/${props.blogId}`).then(res => {
    if (res.data.code === 0) {
      commentList.value = res.data.data
      loading.value = false
      return
    }
    message.error(res.data.message)
  })
}

// 监听blogID，判断是否可以获取数据
watch(() => props.blogId, (value, oldValue) => {
  if (value !== 0) {
    getComments()
  }
})
watch(() => props.authorId, (value, oldValue) => {
  if (value !== 0) {
    authorId.value = value;
  }
})
</script>

<style scoped>

</style>